﻿using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Security;

namespace YougeBookmark.Utilities
{
    /// <summary>
    /// 注册表操作助手类（需要管理员权限）
    /// </summary>
    public static class RegistryHelper
    {
        // 注册表根路径
        private const string ShellPath = @"*\shell\YougeBookmark";
        private const string CommandPath = ShellPath + @"\command";

        /// <summary>
        /// 获取应用程序完整路径（带自动引号转义）
        /// </summary>
        private static string ApplicationPath
        {
            get
            {
                var path = Assembly.GetEntryAssembly()?.Location;
                if (string.IsNullOrWhiteSpace(path))
                    throw new FileNotFoundException("无法获取程序路径");

                // 处理路径中的空格
                return $"\"{path}\"";
            }
        }

        /// <summary>
        /// 安装右键菜单项
        /// </summary>
        /// <exception cref="SecurityException">权限不足时抛出</exception>
        public static void InstallContextMenu()
        {
            try
            {
                // 创建主菜单项
                using (var shellKey = Registry.ClassesRoot.CreateSubKey(ShellPath))
                {
                    shellKey.SetValue("MUIVerb", "优哥书签");    // 显示名称
                    shellKey.SetValue("Icon", $"{ApplicationPath},0"); // 使用第一个图标
                    shellKey.SetValue("Extended", "");          // 仅Shift+右键时显示
                }

                // 创建命令项
                using (var cmdKey = Registry.ClassesRoot.CreateSubKey(CommandPath))
                {
                    cmdKey.SetValue("", $"{ApplicationPath}"); // 执行命令
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                throw new SecurityException("需要管理员权限操作注册表", ex);
            }
        }

        /// <summary>
        /// 卸载右键菜单项
        /// </summary>
        public static bool UninstallContextMenu()
        {
            try
            {
                // 递归删除注册表项
                Registry.ClassesRoot.DeleteSubKeyTree(ShellPath);
                return true;
            }
            catch (ArgumentException ex) when (ex.Message.Contains("不存在"))
            {
                Debug.WriteLine("注册表项不存在");
                return false;
            }
            catch (SecurityException ex)
            {
                Debug.WriteLine($"权限错误: {ex.Message}");
                return false;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"删除失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 检查是否已安装
        /// </summary>
        public static bool CheckInstalled()
        {
            using (var key = Registry.ClassesRoot.OpenSubKey(CommandPath))
            {
                return key?.GetValue("")?.ToString()
                    .Equals(ApplicationPath, StringComparison.OrdinalIgnoreCase) ?? false;
            }
        }
    }
}